// 模拟OSS上传实现，用于测试
import { OSS_CONFIG, generateFileName, validateFileType, validateFileSize } from './ossConfig'

// 上传进度回调类型
export type UploadProgressCallback = (status: UploadStatus) => void

// 上传结果类型
export interface UploadResult {
  success: boolean
  url?: string
  error?: string
  fileName?: string
  uploadId?: string // 分片上传ID，用于断点续传
  fileSize?: number // 文件大小
  uploadTime?: number // 上传耗时
}

// 上传状态类型
export interface UploadStatus {
  isUploading: boolean
  progress: number
  uploadedBytes: number
  totalBytes: number
  speed: number // 上传速度 (bytes/s)
  remainingTime: number // 剩余时间 (秒)
  error?: string
}

// 计算上传速度和剩余时间
const calculateSpeedAndTime = (
  uploadedBytes: number,
  totalBytes: number,
  startTime: number
): { speed: number; remainingTime: number } => {
  const elapsed = (Date.now() - startTime) / 1000 // 秒
  const speed = uploadedBytes / elapsed // bytes/s
  const remainingBytes = totalBytes - uploadedBytes
  const remainingTime = remainingBytes / speed // 秒
  
  return {
    speed: isFinite(speed) ? speed : 0,
    remainingTime: isFinite(remainingTime) ? remainingTime : 0
  }
}

// 模拟上传单文件
export const uploadSingleFile = async (
  file: File,
  onProgress?: UploadProgressCallback
): Promise<UploadResult> => {
  const startTime = Date.now()
  
  try {
    // 验证文件类型
    if (!validateFileType(file)) {
      return {
        success: false,
        error: '不支持的文件类型，请上传图片文件',
        fileSize: file.size
      }
    }

    // 验证文件大小
    if (!validateFileSize(file)) {
      return {
        success: false,
        error: `文件大小不能超过 ${OSS_CONFIG.maxFileSize / 1024 / 1024}MB`,
        fileSize: file.size
      }
    }

    const fileName = generateFileName(file.name)
    const objectKey = `${OSS_CONFIG.uploadPath}${fileName}`

    // 模拟上传进度
    if (onProgress) {
      for (let i = 0; i <= 100; i += 10) {
        await new Promise(resolve => setTimeout(resolve, 100))
        const uploadedBytes = Math.round((i / 100) * file.size)
        const { speed, remainingTime } = calculateSpeedAndTime(uploadedBytes, file.size, startTime)
        
        onProgress({
          isUploading: true,
          progress: i,
          uploadedBytes,
          totalBytes: file.size,
          speed,
          remainingTime
        })
      }
    }

    // 模拟上传成功
    const mockUrl = `https://${OSS_CONFIG.bucket}.${OSS_CONFIG.region}.aliyuncs.com/${objectKey}`
    
    return {
      success: true,
      url: mockUrl,
      fileName: objectKey,
      uploadId: `mock_upload_${Date.now()}`,
      fileSize: file.size,
      uploadTime: Date.now() - startTime
    }
  } catch (error) {
    console.error('上传失败:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : '上传失败',
      fileSize: file.size,
      uploadTime: Date.now() - startTime
    }
  }
}

// 模拟批量上传文件
export const uploadMultipleFiles = async (
  files: File[],
  onProgress?: (fileIndex: number, status: UploadStatus) => void
): Promise<UploadResult[]> => {
  const results: UploadResult[] = []
  
  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    const result = await uploadSingleFile(file, (status) => {
      if (onProgress) {
        onProgress(i, status)
      }
    })
    results.push(result)
  }
  
  return results
}

